package com.ai.wxy.spring.storm.test.drpc;

import lombok.extern.slf4j.Slf4j;
import org.apache.storm.coordination.BatchOutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseBatchBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 统计粉丝量,url,user
 *
 * @author 石头
 * @Date 2019/12/18
 * @Version 1.0
 **/
@Slf4j
public class PartialUniquerBatchBolt extends BaseBatchBolt<Object>{
    private Object requestId;
    private BatchOutputCollector collector;
    // 保存Reach URL的到达者，避免重复
    private Set<String> followers = new HashSet<>();
    @Override
    public void prepare(Map<String, Object> conf, TopologyContext context, BatchOutputCollector collector, Object id) {
        this.requestId = id;
        this.collector = collector;
    }

    @Override
    public void execute(Tuple tuple) {
        String follower = tuple.getString(1);
        if (followers.contains(follower)) {
            return;
        }
        followers.add(tuple.getString(1));
    }

    @Override
    public void finishBatch() {
        log.info("===========>The URL {} Reach Count :{}",requestId,followers.size());
        collector.emit(new Values(requestId, followers.size()));
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("Id", "FollowerCount"));
    }
}
